package bsf.baseservice.businessmq.producter;

import bsf.baseservice.businessmq.common.BusinessMQConfig;
import bsf.baseservice.businessmq.systemruntime.CommonHelper;
import bsf.baseservice.businessmq.systemruntime.log.LogHelper;
import bsf.baseservice.businessmq.systemruntime.BusinessMQException;
import bsf.baseservice.businessmq.systemruntime.log.ErrorLogHelper;

import java.util.Map;

/** 
 简单Producter连接池
 单个mqpath只用一个连接
 
*/
public class ProducterPoolHelper implements AutoCloseable
{
	private static java.util.HashMap<String, ProducterProvider> pool = new java.util.HashMap<String, ProducterProvider>();
	private static Object poollock = new Object();
	private static Object singletonlock = new Object();
	private static ProducterPoolHelper singleton = null;

	private ProducterPoolHelper()
	{
	}

	/** 
	 从连接池中获取生产者
	 
	 @param config
	 @param mqpath
	 @return 
	*/
	public static ProducterProvider getPool(BusinessMQConfig config, String mqpath)
	{
		//创建单例
		if (singleton == null)
		{
			synchronized (singletonlock)
			{
				if (singleton == null)
				{
					singleton = new ProducterPoolHelper();
					Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
						@Override
						public void run() {
							try
							{
								if (singleton != null)
								{
									singleton.close();
								}
								LogHelper.writeLine(-1, "", "addShutdownHook", String.format("当前java进程退出时释放生产者完毕,服务器ip地址:%1$s", CommonHelper.getDefaultIP()));
							}
							catch (Exception exp)
							{
								ErrorLogHelper.writeLine(-1, "", "addShutdownHook", String.format("当前java进程退出时释放生产者连接池出错,服务器ip地址:%1$s", CommonHelper.getDefaultIP()), exp);
								//throw exp;
								System.out.println("当前java进程退出时释放生产者连接池出错");
							}
						}
					}));
				}
			}
		}
		//查找生产者
		ProducterProvider provider = null;
		mqpath = mqpath.toLowerCase();
		if (pool.containsKey(mqpath))
		{
			provider = pool.get(mqpath);
		}
		if (provider == null)
		{
			synchronized (poollock)
			{
				if (pool.containsKey(mqpath))
				{
					provider = pool.get(mqpath);
				}
				if (provider == null)
				{
					ProducterProvider pt = new ProducterProvider();
					pt.Config = config;
					pt.setMQPath(mqpath);
					pt.open();
					pool.put(mqpath, pt);
					provider = pool.get(mqpath);
				}
			}
		}
		return provider;
	}

	public  void close()
	{
		if (singleton != null)
		{
			Exception firstexp = null;
			for (Map.Entry<String,ProducterProvider> item : pool.entrySet())
			{
				try
				{
					if (item.getValue() != null)
					{
						item.getValue().close();
					}
				}
				catch (Exception exp)
				{
					if (firstexp == null)
					{
						firstexp = exp;
					}
				}
			}
			pool = new java.util.HashMap<>();
			singleton = null;
			if (firstexp != null)
			{
				throw new BusinessMQException("close失败",firstexp);
			}
		}
	}
}